package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.sso.mapper.UserMapper;
import com.tanhua.sso.pojo.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Value("${jwt.secret}")
    private String secret;

    /**
     * 用户登录
     *
     * @param phone
     * @param code
     * @return
     */
    public String login(String phone, String code) {
        String redisKey = "CHECK_CODE_" + phone;
        boolean isNew = false;
        //如果验证码在redis中不存在,返回空
        if (!StringUtils.equals(code, this.redisTemplate.opsForValue().get(redisKey))) {
            return null;//验证错误
        }
        //丢弃验证码
        this.redisTemplate.delete(redisKey);
        //根据mobile查询数据库
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", phone);
        User user = this.userMapper.selectOne(wrapper);
        //在mysql中判断是否为新用户,如果是.就进行注册,直接存入到数据库
        if (null == user) {
            user = new User();
            user.setMobile(phone);
            user.setPassword("123456");
           this.userMapper.insert(user);
            isNew = true;
        }
        //生成token
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("id", user.getId());

        // 生成token
        String jwt = Jwts.builder()
                .setClaims(claims) //payload，存放数据的位置，不能放置敏感数据，如：密码等
                .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                .setExpiration(new Date(System.currentTimeMillis() + 300000000)) //设置过期时间，30秒后过期
                .compact();
        //发送用户登陆成功的消息
        try {
            Map<String,Object>msg=new HashMap<>();
            msg.put("id",user.getId() );
            msg.put("date",System.currentTimeMillis() );
            rocketMQTemplate.convertAndSend("tanhua-sso-login", msg);
        } catch (MessagingException e) {
           log.error("发送消息失败",e );
        }
        return jwt+"|"+isNew;
    }

    public User queryUserBytoken(String token) {
        //通过token解析数据
        try {
            // 通过token解析数据
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
            //需要返回user对象中的mobile,需要查询数据库获取到mobile数据
            //如果每次都查询数据库,必然导致性能问题,需要对用户的手机号进行缓存炒作
            //数据缓存是,需要设置过期事件,过期事件要与token的事件一致
            //如果用户修改了手机号,需要同步修改redis中的数据
            User user=new User();
            user.setId(Long.valueOf(body.get("id").toString()));
            String redisKey="TANHUA_USER_MOBILE_"+user.getId();
            //判断redis中是否存在
            if(this.redisTemplate.hasKey(redisKey)){
                String mobile = this.redisTemplate.opsForValue().get(redisKey);
                user.setMobile(mobile);
            }else {
                //先查询数据库,然后放到redis中
                User user1 = this.userMapper.selectById(user.getId());
                user.setMobile(user1.getMobile());
                //将手机号放到redis中
                     //获取token的过期事件/{mobile=1333333333, id=2, exp=1605513392}
                long timeout=Long.valueOf(body.get("exp").toString())*1000-System.currentTimeMillis();
                this.redisTemplate.opsForValue().set(redisKey, user1.getMobile(),timeout,TimeUnit.MICROSECONDS);
            }
            return user;
        } catch (ExpiredJwtException e) {
            System.out.println("token已经过期！"+token);
        } catch (Exception e) {
            System.out.println("token不合法！"+token);
        }
        return null;
    }
}
